package com.whz.serial;

import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;

/**
 * @Author: sinosoft
 * @Description: 用序列化代理代替序列化实例
 * @Date: Create in 12:38 2021/5/19
 * @Modified By:
 */
public final class Period implements Serializable {
    private final Date start;
    private final Date end;

    public Period(Date start, Date end) {
        if(start.compareTo(end) > 0) {
            throw new IllegalArgumentException("开始时间: " + start + "在结束时间之后: " + end);
        }
        this.start = start;
        this.end = end;
    }

    public Date start() {
        return start;
    }

    public Date end() {
        return end;
    }

    @Override
    public String toString() {
        return "Period{" +
                "开始时间=" + start +
                ", 结束时间=" + end +
                '}';
    }

    /*步骤一: 创建私有静态代理类,属性与外围类保持一致*/
    private static class SerializationProxy implements Serializable {

        private static final long serialVersionUID = 4206869806798390371L;

        private final Date start;
        private final Date end;

        public SerializationProxy(Period p) {
            this.start = p.start;
            this.end = p.end;
        }
        /*步骤四:使用外围类的构造方法实例化外围类,不会破坏原本的构造器规则*/
        private Object readResolve() {
            return new Period(start, end);
        }
    }
    /*步骤二: 编写writeReplace方法,将序列化工作交给内部类*/
    private Object writeReplace() {
        return new SerializationProxy(this);
    }
    /*步骤三: 防止客户端直接使用外围类进行反序列化*/
    private void readObject(ObjectInputStream stream)
            throws InvalidObjectException {
        throw new InvalidObjectException("请使用序列化代理");
    }
}
